import React, { Component } from "react";
import {
  Button,
  Form,
  Input,
  Select,
  Switch,
  message,
  Spin
  // Radio
} from "antd";
import { connect } from "dva";
import moment from "moment";
import dataInfo from "./data";
// import TopInfo from "./components/TopInfo";
import SelectModal from "../../recommendCenter/add/components/SelectModal";
import BottomInfo from "./components/BottomInfo";
import styles from "./MessageAdd.less";
import FixedBottomWrapper from "../../../components/FixedBottomWrapper";
import {
  queryUnBindMsgSourceTemplate,
  getMessageTemplateList
} from "../services/messageTemplateApi";

const { TextArea } = Input;
// const { Option } = Select;

@connect(stores => ({
  coldata: stores.user,
  dsDetail: stores.adddataSource,
  messageSave: stores.saveMessage,
  EditplanData: stores.addPlan,
  channelDictionaryModel: stores.channelDictionaryModel
}))
@Form.create()
class MessageAdd extends Component {
  state = {
    workDisable: true,
    startTime: "",
    endTime: "",
    category: 1,
    num: "",
    workTime: "",
    ruleType: "",
    ruleDisable: true,
    ruleChannel: "",
    ownerDeptName: "",
    manager: [],
    managerName: [],
    selectVisible: false,
    timeVisible: false,
    radioVisible: false,
    msgSourceId: "",
    loadingEdit: false,
    ownerDept: "",
    channelName: "",
    channleType: null,
    resendChannelName: "",
    messageType: null,
    isUseTemplate: false,
    templateList: [],
    initChannelType: null,
    initTemplateItem: null
  };

  componentDidMount() {
    const { dispatch } = this.props;
    // dispatch({
    //   type: "channelDictionaryModel/channelsTypes",
    //   payload: {}
    // });
    dispatch({ type: "addPlan/getPushChannel", payload: {} });
    dispatch({ type: "saveMessage/listMessageTypes", payload: {} });

    dispatch({
      type: "adddataSource/getOrgList",
      payload: {}
    });

    getMessageTemplateList({ pageNum: 1, pageSize: 1000000 }).then(res => {
      if (res.success) {
        this.setState({ templateList: res.datas });
      } else {
        message.error(res.errMsg);
      }
    });
    this.setState({ loadingEdit: true });
    setTimeout(() => {
      this.setValue();
      this.setState({ loadingEdit: false });
    }, 600);
  }

  confirm = (e, desc) => {
    this.setState({ managerName: desc, manager: e, selectVisible: false });
    this.props.form.setFieldsValue({ owner: 1 });
  };

  setValue = () => {
    const { messageSave } = this.props;
    const { key } = messageSave;
    const {
      coldata: {
        userInfo: {
          userId = "",
          userName = "",
          department = "",
          departmentName = ""
        } = {}
      } = {},
      dispatch
    } = this.props;
    if (key.operate === "add") {
      this.setState({
        manager: [userId],
        managerName: [userName],
        ownerDept: department,
        ownerDeptName: departmentName
      });
      this.props.form.setFieldsValue({ owner: 1 });
    }
    if (key.operate === "mod") {
      dispatch({
        type: "saveMessage/getDetail",
        payload: { msgSourceId: key.msgSourceId }
      }).then(() => {
        this.getDetail(key.msgSourceId);
      });
    }
  };

  getDetail = async msgSourceId => {
    const { messageSave } = this.props;
    const { detailMessage = {} } = messageSave;
    const { workTime } = dataInfo.setWork(detailMessage);

    const res = await queryUnBindMsgSourceTemplate(
      detailMessage.pushChannelType
    );
    if (res.success) {
      let ruleType = "";
      if (
        detailMessage.resendChannelId &&
        detailMessage.resendChannelId === detailMessage.pushChannelId
      ) {
        ruleType = 1;
      } else if (
        detailMessage.resendChannelId &&
        detailMessage.resendChannelId !== "" &&
        detailMessage.resendChannelId !== detailMessage.pushChannelId
      ) {
        ruleType = 2;
      } else {
        ruleType = "";
      }
      const isUseTemplate = typeof detailMessage.primaryId === "number";
      const initTemplateItem = {
        id: detailMessage.primaryId,
        name: detailMessage.templateName
      };
      this.setState(
        {
          workTime,
          startTime: workTime === 6 ? detailMessage.startTime : "",
          endTime: workTime === 6 ? detailMessage.endTime : "",
          workDisable: workTime !== 6,
          channelName: detailMessage.pushChannelName
            ? detailMessage.pushChannelName
            : "",
          category: !detailMessage.flowControlTimeUnit
            ? 1
            : detailMessage.flowControlTimeUnit,
          num: !detailMessage.flowControlCountLimit
            ? ""
            : detailMessage.flowControlCountLimit,
          manager: [
            detailMessage.owner && JSON.parse(detailMessage.owner)
              ? JSON.parse(detailMessage.owner)[0].key
              : ""
          ],
          managerName: [
            detailMessage.owner && JSON.parse(detailMessage.owner)
              ? JSON.parse(detailMessage.owner)[0].name
              : ""
          ],
          ownerDept: detailMessage.ownerDept,
          ownerDeptName: detailMessage.ownerDeptName,
          msgSourceId,
          ruleChannel: ruleType === 1 ? "" : detailMessage.resendChannelId,
          resendChannelName: detailMessage.resendChannelName,
          ruleType,
          ruleDisable:
            detailMessage.resendChannelId === detailMessage.pushChannelId ||
            !detailMessage.resendChannelId ||
            detailMessage.resendChannelId === "",
          channelType: detailMessage.pushChannelType,
          initChannelType: detailMessage.pushChannelType,
          isUseTemplate,
          // templateList: isUseTemplate
          //   ? [...res.datas, initTemplateItem]
          //   : res.datas,
          initTemplateItem: isUseTemplate ? initTemplateItem : null
        },
        () => {
          this.props.form.setFieldsValue({
            owner: 1,
            messageName: detailMessage.sourceName,
            messageType: detailMessage.messageType,
            templatePrimaryId: detailMessage.primaryId,
            templateId: detailMessage.templateId,
            channelType: String(detailMessage.pushChannelType),
            channelName: detailMessage.pushChannelId,
            messageDescription: detailMessage.sourceDescription,
            isEnabled: detailMessage.isEnabled === "Y"
          });
        }
      );
    } else {
      message.error(res.errMsg);
    }
  };

  closeModal = () => {
    this.setState({
      selectVisible: false
    });
  };

  departGet = (e, departmentName) => {
    this.setState({
      ownerDeptName: departmentName[0]
    });
  };

  handleSubmit = e => {
    const { messageSave } = this.props;
    const { key } = messageSave;
    const {
      workTime,
      startTime,
      endTime,
      num,
      // ruleType,
      // ruleChannel,
      // resendChannelName,
      ownerDeptName,
      category,
      manager,
      managerName,
      msgSourceId,
      channelName,
      templateList
    } = this.state;
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      if (workTime === "") {
        this.setState({
          radioVisible: true
        });
        return;
      }
      if (workTime === 6 && startTime === "") {
        this.setState({
          timeVisible: true
        });
        return;
      }

      if (!err) {
        const { dispatch } = this.props;
        // let resendChannelId = "";
        // let resendChannelTmp = "";
        // if (ruleType === 1) {
        //   resendChannelId = values.channelName;
        //   resendChannelTmp = channelName;
        // }
        // if (ruleType === 2) {
        //   resendChannelId = ruleChannel;
        //   resendChannelTmp = resendChannelName;
        // }
        // if (ruleType === "") {
        //   resendChannelId = "";
        //   resendChannelTmp = "";
        // }
        const payload = {
          msgSourceId,
          sourceName: values.messageName,
          pushChannelType: values.channelType,
          pushChannelId: values.channelName,
          ownerRequest: [{ key: manager[0], name: managerName[0] }],
          ownerDept: values.ownerDept,
          sourceDescription: values.messageDescription,
          flowControlTimeUnit: category,
          flowControlCountLimit: num,
          ownerDeptName,
          pushChannelName: channelName,
          // resendChannelId,
          messageType: values.messageType,
          // resendChannelName: resendChannelTmp,
          sourceType: workTime,
          startTime: dataInfo.workTimeClassify(workTime, startTime, endTime)
            .startTime,
          endTime: dataInfo.workTimeClassify(workTime, startTime, endTime)
            .endTime,
          // templatePrimaryId: isUseTemplate ? values.templatePrimaryId : null,
          sourceId: values.sourceId,
          templateId: values.templateId,
          isEnabled: values.isEnabled ? "Y" : "N",
          templateCode: templateList.find(
            d => d.templateId === values.templateId
          ).templateCode,
          templateName: templateList.find(
            d => d.templateId === values.templateId
          ).templateName
        };
        dispatch({
          type:
            key.operate === "add"
              ? "saveMessage/saveSendMessage"
              : "saveMessage/editMessage",
          payload
        }).then(res => {
          const { errCode, errMsg } = res;
          if (errCode === 0) {
            const { history } = this.props;
            message.success("操作成功");
            history.push("/messageCenter/messageManager/messageSource");
          } else {
            message.error(errMsg);
          }
        });
      }
    });
  };

  getChannel = e => {
    const { EditplanData } = this.props;
    const { channelList = [] } = EditplanData;
    let channelName = "";
    channelList.forEach(item => {
      if (String(item.pushChannelId) === String(e)) {
        channelName = item.description;
      }
    });
    this.setState({
      ruleChannel: e,
      resendChannelName: channelName
    });
  };

  getRule = e => {
    this.setState({
      ruleType: e.target.value,
      ruleDisable: e.target.value !== 2
    });
  };

  getTimeCategory = e => {
    this.setState({
      category: e
    });
  };

  getNumber = e => {
    this.setState({
      num: e
    });
  };

  onBack = () => {
    const { history } = this.props;
    history.goBack(-1);
    /*
    Modal.confirm({
      title: "是否直接关闭此消息源？",
      onOk() {
        history.push("/messageCenter/messageManager/messageSource");
      },
      onCancel() {}
    });
    */
  };

  getWorkTimeType = e => {
    this.setState({
      workTime: e.target.value,
      workDisable: e.target.value !== 6,
      radioVisible: false,
      timeVisible: false
    });
  };

  channelSet = e => {
    const { EditplanData } = this.props;
    const { channelList = [] } = EditplanData;
    let channelName = "";
    channelList.forEach(item => {
      if (String(item.pushChannelId) === String(e)) {
        channelName = item.description;
      }
    });
    this.setState({ channel: e, channelName });
  };

  chooseChannelType = async e => {
    if (Number(e) !== 4) {
      this.setState({
        channelType: Number(e)
      });
      return;
    }
    const res = await queryUnBindMsgSourceTemplate(Number(e));
    // const { initChannelType, initTemplateItem } = this.state;
    if (res.success) {
      this.setState({
        channelType: Number(e)
        // templateList:
        //   Number(e) === initChannelType && initTemplateItem
        //     ? [...res.datas, initTemplateItem]
        //     : res.datas
      });
      this.props.form.setFieldsValue({
        channelName: undefined,
        messageType: undefined,
        templatePrimaryId: undefined
      });
    } else {
      message.error(res.errMsg);
    }
  };

  getWorkTime = self => {
    this.setState({
      startTime: moment(self[0]).format("YYYY-MM-DD HH:mm:ss"),
      endTime: moment(self[1]).format("YYYY-MM-DD HH:mm:ss"),
      timeVisible: false
    });
  };

  render() {
    const {
      // dsDetail,
      messageSave,
      EditplanData,
      channelDictionaryModel = {}
    } = this.props;
    const { channelList = [] } = EditplanData;
    const { getFieldDecorator } = this.props.form;
    // const { orgTree = [] } = dsDetail;
    const { manager, managerName, selectVisible, timeVisible } = this.state;
    const { radioVisible, loadingEdit, channelType } = this.state;
    const {
      workDisable,
      num,
      startTime,
      endTime,
      workTime,
      ruleDisable,
      ruleType,
      ruleChannel,
      category,
      // isUseTemplate,
      templateList
    } = this.state;
    const { detailMessage = {}, loading, messageTypeList = [] } = messageSave;
    const { formItemLayout } = dataInfo;
    const { channelsTypesData = [] } = channelDictionaryModel;
    // const radioStyle = {
    //   display: "block",
    //   height: "40px",
    //   lineHeight: "40px"
    // };
    return (
      <FixedBottomWrapper
        className={styles.root}
        footer={
          <div className={styles.btns}>
            {/* <Button
              type="primary"
              style={{ marginLeft: 16 }}
              // htmlType="submit"
              onClick={e => this.handleSubmit(e, "submit")}
            >
              申请发布
            </Button> */}
            <Button
              type="primary"
              style={{ marginLeft: 8, marginRight: 8 }}
              // htmlType="submit"
              onClick={e => this.handleSubmit(e)}
            >
              保存
            </Button>
            <Button onClick={this.onBack}>取消</Button>
          </div>
        }
      >
        <Spin spinning={loadingEdit || loading}>
          <div className={styles.topInfo}>
            <SelectModal
              select={manager}
              selectdesc={managerName}
              visible={selectVisible}
              closeModal={this.closeModal}
              confirm={this.confirm}
              isMutiple={false}
              manager={true}
            />
            <span className={styles.basic}>基本信息</span>
            <Form onSubmit={this.handleSubmit}>
              <Form.Item {...formItemLayout} label="消息源名称">
                {getFieldDecorator("messageName", {
                  rules: [
                    {
                      required: true,
                      message: "消息源名称不能为空"
                    },
                    {
                      max: 20,
                      message: "消息源名称少于20个字"
                    }
                  ]
                })(
                  <Input
                    style={{ width: 466 }}
                    placeholder="请输入消息源名称"
                  />
                )}
              </Form.Item>
              <Form.Item {...formItemLayout} label="消息源ID">
                {getFieldDecorator("sourceId")(
                  <span style={{ color: "rgba(0,0,0,0.65)", fontSize: 14 }}>
                    {detailMessage.sourceId ? detailMessage.sourceId : "---"}
                  </span>
                )}
              </Form.Item>
              <Form.Item {...formItemLayout} label="渠道类型">
                {getFieldDecorator("channelType", {
                  rules: [
                    {
                      required: true,
                      message: "请选择渠道类型"
                    }
                  ]
                })(
                  <Select
                    placeholder="请选择渠道类型"
                    style={{ width: 466 }}
                    onChange={this.chooseChannelType}
                    getPopupContainer={triggerNode => triggerNode.parentNode}
                  >
                    {channelsTypesData.map((item, index) => (
                      <Select.Option key={index} value={`${item.value}`}>
                        {item.des}
                      </Select.Option>
                    ))}
                  </Select>
                )}
              </Form.Item>
              <Form.Item {...formItemLayout} label="渠道名称">
                {getFieldDecorator("channelName", {
                  rules: [
                    {
                      required: true,
                      message: "请选择渠道名称"
                    }
                  ]
                })(
                  <Select
                    placeholder="请选择渠道名称"
                    style={{ width: 466 }}
                    onChange={this.channelSet}
                    getPopupContainer={triggerNode => triggerNode.parentNode}
                  >
                    {channelList
                      .filter(item => item.channelType * 1 === channelType)
                      .map(item => (
                        <Select.Option
                          value={item.pushChannelId * 1}
                          key={item.pushChannelId}
                        >
                          {item.description}
                        </Select.Option>
                      ))}
                  </Select>
                )}
              </Form.Item>
              <Form.Item {...formItemLayout} label="消息类型">
                {getFieldDecorator("messageType", {
                  rules: [
                    {
                      required: true,
                      message: "请选择消息类型"
                    }
                  ]
                })(
                  <Select placeholder="请选择消息类型" style={{ width: 466 }}>
                    {messageTypeList
                      .filter(item => item.pushChannelType * 1 === channelType)
                      .map(item => (
                        <Select.Option
                          value={item.messageType}
                          key={item.messageType}
                        >
                          {item.messageTypeName}
                        </Select.Option>
                      ))}
                  </Select>
                )}
              </Form.Item>
              <Form.Item {...formItemLayout} label="消息模板列表">
                {getFieldDecorator("templateId", {
                  rules: [
                    {
                      required: true,
                      message: "请选择模板"
                    }
                  ]
                })(
                  <Select
                    placeholder="请选择模板"
                    style={{ width: 466 }}
                    getPopupContainer={triggerNode => triggerNode.parentNode}
                    showSearch
                    filterOption={(input, option) =>
                      option.props.children
                        .toLowerCase()
                        .indexOf(input.toLowerCase()) >= 0
                    }
                  >
                    {templateList.map(item => (
                      <Select.Option
                        value={item.templateId}
                        key={item.templateId}
                      >
                        {item.templateName}
                      </Select.Option>
                    ))}
                  </Select>
                )}
              </Form.Item>
              {/* {Number(channelType) === 4 && (
                <Form.Item {...formItemLayout} label="消息模板">
                  <Radio.Group
                    value={isUseTemplate}
                    onChange={e =>
                      this.setState({ isUseTemplate: e.target.value })
                    }
                  >
                    <Radio style={radioStyle} value={false}>
                      不启用消息模板
                    </Radio>
                    <Radio style={radioStyle} value={true}>
                      选择
                      {getFieldDecorator("templatePrimaryId")(
                        <Select
                          style={{ width: 220, margin: "0 8px" }}
                          disabled={!isUseTemplate}
                        >
                          {templateList.map(item => (
                            <Option key={item.id} value={item.id}>
                              {item.name}
                            </Option>
                          ))}
                        </Select>
                      )}
                      消息模板进行发送
                    </Radio>
                  </Radio.Group>
                </Form.Item>
              )} */}
              {/* <Form.Item {...formItemLayout} label="管理员">
                {getFieldDecorator("owner", {
                  rules: [
                    {
                      required: true,
                      message: "请选择管理员"
                    }
                  ]
                })(
                  <div>
                    <Input
                      style={{ width: 466 }}
                      placeholder="请选择管理员"
                      onClick={() => {
                        this.setState({ selectVisible: true });
                      }}
                      value={this.state.managerName}
                    />
                  </div>
                )}
              </Form.Item>
              <Form.Item {...formItemLayout} label="归属部门">
                {getFieldDecorator("ownerDept", {
                  rules: [
                    {
                      required: true,
                      message: "请选择归属部门"
                    }
                  ],
                  initialValue: detailMessage.ownerDept
                    ? detailMessage.ownerDept
                    : this.state.ownerDept
                })(
                  <TreeSelect
                    treeData={orgTree}
                    onChange={this.departGet}
                    style={{ width: 466 }}
                    dropdownStyle={{ maxHeight: 350, overflow: "auto" }}
                    showCheckedStrategy="SHOW_PARENT"
                    placeholder="请选择归属部门"
                  />
                )}
              </Form.Item> */}
              <Form.Item {...formItemLayout} label="是否启用">
                {getFieldDecorator("isEnabled", {
                  valuePropName: "checked"
                })(<Switch />)}
              </Form.Item>
              <Form.Item {...formItemLayout} label="消息源描述">
                {getFieldDecorator("messageDescription", {
                  rules: [
                    {
                      max: 200,
                      message: "消息源描述少于200个字"
                    }
                  ]
                })(
                  <TextArea
                    style={{ width: 466, height: 120 }}
                    placeholder="请输入消息源描述"
                  />
                )}
              </Form.Item>
            </Form>
          </div>
          <BottomInfo
            getRule={this.getRule}
            getFlux={this.getFlux}
            getWorkTime={this.getWorkTime}
            getWorkTimeType={this.getWorkTimeType}
            workDisable={workDisable}
            getTimeCategory={this.getTimeCategory}
            getNumber={this.getNumber}
            num={num}
            startTime={startTime}
            endTime={endTime}
            workTime={workTime}
            ruleDisable={ruleDisable}
            ruleType={ruleType}
            category={category}
            ruleChannel={ruleChannel}
            timeVisible={timeVisible}
            radioVisible={radioVisible}
            channelList={channelList}
            getChannel={this.getChannel}
          />
        </Spin>
      </FixedBottomWrapper>
    );
  }
}

export default MessageAdd;
